#include <stdio.h>
#include <libxml/parser.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <netdb.h> 
#include "sms_basic_types.h"


void error(const char *msg)
{
    perror(msg);
    exit(0);
}


int main(int argc, char *argv[])
{
    int sockfd, portno, n, size, flag, ret;
    struct sockaddr_in serv_addr;
    struct hostent *server;
    FILE *file;
    char * file_buffer;
    size_t result;
    int header = 0;

    char buffer[256];
    portno = 8081;
    sockfd = socket(AF_INET, SOCK_STREAM, 0);
 ret = setsockopt(sockfd, IPPROTO_TCP, TCP_NODELAY, (char *)&flag, sizeof(flag) );
    if (sockfd < 0) 
        error("ERROR opening socket");
    server = gethostbyname("127.0.0.1");
    if (server == NULL) {
        fprintf(stderr,"ERROR, no such host\n");
        exit(0);
    }
    bzero((char *) &serv_addr, sizeof(serv_addr));
    serv_addr.sin_family = AF_INET;
    bcopy((char *)server->h_addr, 
         (char *)&serv_addr.sin_addr.s_addr,
         server->h_length);
    serv_addr.sin_port = htons(portno);
    if (connect(sockfd,(struct sockaddr *) &serv_addr,sizeof(serv_addr)) < 0) 
        error("ERROR connecting");
    printf("Please enter the message: ");
    bzero(buffer,256);
   
    file = fopen("testXML.xml", "r");
      // obtain file size:
    if (file == NULL)
    {
        fprintf(stderr, "no such file : %s", "testXML.xml");
        exit(0);    
    }
    fseek (file , 0 , SEEK_END);
    size = ftell (file);
    rewind (file);

    // allocate memory to contain the whole file:
    file_buffer = (char*) malloc (sizeof(char)*size);
    if (file_buffer == NULL) {fputs ("Memory error",stderr); exit (2);}

    // copy the file into the buffer:
    result = fread (file_buffer, 1, size, file);
    if (result != size) {fputs ("Reading error",stderr); exit (3);}

    /* the whole file is now loaded in the memory buffer. */

    // terminate
    fclose (file);
    xmlDocPtr doc = xmlParseFile("testXML.xml");
    xmlNodePtr root = xmlDocGetRootElement(doc);
    if (root == NULL) fprintf(stderr, "can not get root");  
    fprintf(stderr, "send size is %d", size);
    header = size; 
    n = write(sockfd, &header, sizeof(header));
    fprintf(stderr, "send header size is %d", n);
    if (n < 0) 
         error("ERROR writing to socket");
    bzero(buffer,256);
    n = write(sockfd, file_buffer, size);
    fprintf(stderr, "send file size is %d", n);
    free (file_buffer);

    n = read(sockfd,buffer,255);
    if (n < 0) 
         error("ERROR reading from socket");
    printf("%s\n",buffer);
    close(sockfd);
    return 0;
}
